package com.bawei.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.JavascriptInterface
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.RouterPath
import com.bawei.common.base.BaseActivity
import com.bawei.common.dialog.AppUpdateDialog
import com.bawei.main.databinding.ActivityMainBinding
import com.tencent.mmkv.MMKV
import java.util.Objects


@Route(path = RouterPath.PATH_MAIN)
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private var mBackClickCount = 0
    private lateinit var mAppUpdateDialog: AppUpdateDialog
    private var hasUnGranted = false

    //应用需要的权限
    private var needUserPermissions = arrayListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.RECORD_AUDIO)
    //未授权的权限
    private var unGrantPermission = mutableListOf<String>()

    override fun getLayoutId(): Int = R.layout.activity_main


    override fun initViews() {
        //模拟APP更新弹窗
        appUpdateDialog()
        //初始化WebView
        x5WebViewInit()
    }

    private fun autoRequestPermission(): Boolean {
        //Android6.0以上要动态申请用户权限
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //清理历未授权的权限
            unGrantPermission.clear()
            //检查用户是否同意了权限
            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if(state == PackageManager.PERMISSION_DENIED){ //用户拒绝的权限
                    unGrantPermission.add(it)
                }
            }
            //发起用户权限授权
            if(unGrantPermission.size > 0){
               requestPermissions(unGrantPermission.toTypedArray(), 100)
               return false
            }
        }
        return true
    }

    private fun x5WebViewInit(){
        //配置基本参数
        var mainUrl =  MMKV.defaultMMKV().decodeString("main_url", "")
        mDataBinding.wbTencent.loadUrl(mainUrl)
        mDataBinding.wbTencent.view.overScrollMode = View.OVER_SCROLL_NEVER
        //设置JS需要交互的接口对象，并指定别名
        mDataBinding.wbTencent.addJavascriptInterface(WebViewJsInterface(), "androidinfo") //别名必须和前端开发人员约定好
        //延迟检查用户权限
        mDataBinding.wbTencent.postDelayed({
            autoRequestPermission()
        }, 1000)
    }


    /**
     * APP更新
     */
    private fun appUpdateDialog(){
        var hasNewApp = MMKV.defaultMMKV().decodeBool("has_new_app", true)
        mAppUpdateDialog = AppUpdateDialog(this)
        if (hasNewApp){
            MMKV.defaultMMKV().encode("has_new_app", false)
            mDataBinding.wbTencent.postDelayed({
                mAppUpdateDialog.show()
            }, 2000)
        }
    }

    /**
     * 打开应用详情页面
     */
    private fun openAppDetailPage(){
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName,null)
        startActivity(intent)
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //再次检查用户权限是否全部同意
        if(requestCode == 100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermission.forEach {
                //判断是否还有未授权的权限
                if(checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }
        }
        //给出权限提示，让用户自己设置
        if(hasUnGranted){
            var builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("权限授权")
            builder.setMessage("没有授权，请到应用详情中设置")
            builder.setPositiveButton("去设置"){ dialog, _ ->
                dialog.dismiss()
                openAppDetailPage()
                hasUnGranted = false
            }
            builder.setNegativeButton("取消"){ dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
            }
            var alertDialog = builder.create()
            alertDialog.show()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        //处理返回按键，回退到上一页
        if(keyCode == KeyEvent.KEYCODE_BACK && mDataBinding.wbTencent.canGoBack()){
            mDataBinding.wbTencent.goBack()
            return true
        }

        //双击返回按钮退出应用
        if(keyCode == KeyEvent.KEYCODE_BACK){
            mBackClickCount += 1
        }

        //提示用户再点击返回按钮退出
        if (mBackClickCount == 1){
            showMessage("再点击一次退出")
            return true
        }

        return super.onKeyDown(keyCode, event)

    }

    override fun onResume() {
        mDataBinding.wbTencent.onResume()
        super.onResume()
    }

    override fun onPause() {
        mDataBinding.wbTencent.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        //清理WebView
        mDataBinding.wbTencent.removeJavascriptInterface("androidinfo")
        mDataBinding.wbTencent.clearCache(true)
        mDataBinding.wbTencent.clearHistory()
        mDataBinding.wbTencent.removeAllViews()
        mDataBinding.wbTencent.destroy()
        super.onDestroy()
    }

    /**
     * 进入业务模块
     */
    private fun jumpModuleActivity(moduleType: String){
        //只有所有权限都同意后才能进入功能页面
        var hasAllPermission = autoRequestPermission()
        if (!hasAllPermission) return

        //根据类型分发跳转到对应页面
        when(moduleType){
            "1","2","3","4","5","6" -> ARouter.getInstance().build(RouterPath.PATH_PROPERTY).withString("moduleType", moduleType).navigation()
            "7","8","9","10" -> ARouter.getInstance().build(RouterPath.PATH_CULTURE).withString("moduleType", moduleType).navigation()
            "11","12" -> ARouter.getInstance().build(RouterPath.PATH_ATTENDANCE).withString("moduleType", moduleType).navigation()
            "13","14","15" -> ARouter.getInstance().build(RouterPath.PATH_AUDIT).withString("moduleType", moduleType).navigation() //物业审核
            else -> showMessage("敬请期待！")
        }
    }

    /**
     * JS调用Android方法类
     */
    inner class WebViewJsInterface{
        @JavascriptInterface
        fun androidparking(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidapply(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidvisit(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpatrol(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnews(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidnoticelist(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddrepair(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidaddnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidnotice(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidsign(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidattendance(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidproperty(id: String) = jumpModuleActivity(id)
        @JavascriptInterface
        fun androidcheckculture(id: String) = jumpModuleActivity(id)

        @JavascriptInterface
        fun androidpeople(id: String) = jumpModuleActivity(id)
    }




}